#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.web.interceptor;

import org.jboss.logging.MDC;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * Created by well on 17/6/9.
 */
@Service
public class LoggerInterceptor implements HandlerInterceptor {

    private static final String REFERER_KEY = "referer";
    private static final String USER_AGENT_KEY = "ua";
    private static final String UID_KEY = "uid";
    private static final String HOST_KEY = "host";
    private static final String URI_KEY = "uri";
    private static final String TRACE_ID_KEY = "traceId";

    private static final String USER_AGENT_NAME = "User-Agent";
    private static final String REFERER_NAME = "Referer";

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestURI = httpServletRequest.getRequestURI();
        String userAgent = httpServletRequest.getHeader(USER_AGENT_NAME);
        String referer = httpServletRequest.getHeader(REFERER_NAME);
        MDC.put(REFERER_KEY,referer);
        MDC.put(HOST_KEY,httpServletRequest.getRemoteAddr());
        MDC.put(UID_KEY,"1");
        MDC.put(USER_AGENT_KEY,userAgent);
        MDC.put(URI_KEY,requestURI);
        MDC.put(TRACE_ID_KEY, UUID.randomUUID().toString().replace("-", ""));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        MDC.clear();
    }
}
